<!-- RecordDetail.vue -->
<template>
    <div class="record-detail">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <van-loading type="spinner" size="24px">加载中...</van-loading>
      </div>
  
      <template v-else>
        <!-- 基础信息卡片 -->
        <div class="info-card">
          <div class="point-info">
            <span class="point-name">{{ record.pointName }}</span>
            <div class="status-info">
              <van-tag :type="getStatusType(record.processStatus)" size="medium">
                {{ getStatusText(record.processStatus) }}
              </van-tag>
            </div>
          </div>
          <div class="check-info">
            <span class="check-label">检查结果:</span>
            <van-tag :type="getCheckResultType(record.checkResult)" size="medium">
              {{ getCheckResultText(record.checkResult) }}
            </van-tag>
          </div>
          <div class="inspector-info">
            <span>检查人: {{ record.inspectorName }}</span>
          </div>
          <div class="time-info">
            <span>检查时间: {{ formatTime(record.createdTime) }}</span>
          </div>
        </div>
  
        <!-- 表单内容区域 -->
        <div class="form-content">
          <div class="section-title">{{ record.form?.name }}</div>
          <!-- 表单项列表 -->
          <div class="form-items">
            <!-- CHECK_STATUS 类型 -->
            <template v-for="item in getItemsByType(record.itemRecords, 'CHECK_STATUS')" :key="item.formItem.id">
              <div class="form-item" :class="{ 'abnormal': item.values[0] === 'ABNORMAL' }">
                <div class="item-label">{{ item.formItem.name }}</div>
                <van-radio-group v-model="item.values[0]" direction="horizontal" disabled>
                  <van-radio name="NORMAL">正常</van-radio>
                  <van-radio name="ABNORMAL">异常</van-radio>
                </van-radio-group>
              </div>
            </template>
  
            <!-- TEXT 类型 -->
            <template v-for="item in getItemsByType(record.itemRecords, 'TEXT')" :key="item.formItem.id">
              <div class="form-item">
                <div class="item-label">{{ item.formItem.name }}</div>
                <van-field
                    v-model="item.values[0]"
                    type="textarea"
                    rows="2"
                    readonly
                    :placeholder="'-'"
                />
              </div>
            </template>
  
            <!-- IMAGE_LIST 类型 -->
            <template v-for="item in getItemsByType(record.itemRecords, 'IMAGE_LIST')" :key="item.formItem.id">
              <div class="form-item">
                <div class="item-label">{{ item.formItem.name }}</div>
                <div class="image-grid">
                  <a-image
                      v-for="(image, index) in item.values"
                      :key="index"
                      :src="getFullImageUrl(image)"
                      width="80"
                      height="80"
                      radius="4"
                      fit="cover"
                  />
                </div>
              </div>
            </template>
          </div>
        </div>
  
        <!-- 处理记录列表 -->
        <div v-if="record.handleRecords && record.handleRecords.length > 0" class="handle-records">
          <div class="section-title">处理记录</div>
          <div class="record-list">
            <div v-for="(handleRecord, index) in record.handleRecords" :key="index" class="handle-record">
              <div class="handle-meta">
                <span class="handler-name">处理人: {{ handleRecord.handlerName }}</span>
                <span class="handle-time">{{ formatTime(handleRecord.handleTime) }}</span>
              </div>
              <div class="handle-status">
                <van-tag :type="getStatusType(handleRecord.processStatus)">
                  {{ getStatusText(handleRecord.processStatus) }}
                </van-tag>
              </div>
              <div class="handle-desc">{{ handleRecord.description }}</div>
              <div v-if="handleRecord.afterImages && handleRecord.afterImages.length > 0" class="handle-images">
                <a-image
                    v-for="(image, imgIndex) in handleRecord.afterImages"
                    :key="imgIndex"
                    :src="getFullImageUrl(image)"
                    :width="80"
                />
              </div>
            </div>
          </div>
        </div>
  
        <!-- 处理表单 -->
        <div v-if="record.checkResult === 'ABNORMAL' && record.processStatus !== 'COMPLETED'" class="handle-form">
          <div class="section-title">处理信息</div>
          <van-field
              v-model="handleForm.description"
              type="textarea"
              disabled
              placeholder="请输入处理说明"
              rows="3"
              class="handle-input"
          />
          <div class="upload-section">
            <div class="upload-label">处理后照片</div>
            <van-uploader
                v-model="handleForm.images"
                multiple
                disabled
                :before-read="beforeRead"
                :after-read="afterRead"
                :max-count="9"
                :max-size="800 * 1024"
                @oversize="onOversize"
            />
          </div>
          <div class="status-select">
            <span class="status-label">处理状态:</span>
            <van-radio-group v-model="handleForm.processStatus" direction="horizontal" disabled>
              <van-radio name="COMPLETED">已处理</van-radio>
              <van-radio name="NO_NEED">无需处理</van-radio>
            </van-radio-group>
          </div>
          <!-- <div class="submit-section">
            <van-button
                type="primary"
                block
                :loading="submitting"
                :disabled="!handleForm.description || handleForm.description.trim() === ''"
                @click="handleSubmit"
            >
              提交处理
            </van-button>
          </div> -->
        </div>
      </template>
  
      <!-- 提交成功弹窗 -->
      <van-dialog
          v-model:show="showSuccess"
          title="提交成功"
          confirmButtonText="返回"
          @confirm="router.back()"
      >
        <div class="success-content">
          <van-icon name="success" class="success-icon" />
          <p>处理信息已提交成功！</p>
        </div>
      </van-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, inject } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import Compressor from 'compressorjs'
  import { filesUpload, getRecordsId, recordHandle } from "@/api/common"
  import { Uploader as VanUploader } from "vant"
  
  const route = useRoute()
  const toast = inject("toast")
  const router = useRouter()
  
  // 状态管理
  const loading = ref(true)
  const submitting = ref(false)
  const record = ref({})
  const showSuccess = ref(false)
  const baseUrl = ref("http://101.68.222.195:9090/image");
  
  // 处理表单数据
  const handleForm = ref({
    description: '',
    images: [],
    processStatus: 'COMPLETED'
  })
  
  // 图片相关处理
  const beforeRead = (file) => {
    return new Promise((resolve) => {
      new Compressor(file, {
        quality: 0.7,
        maxWidth: 1080,
        maxHeight: 1080,
        mimeType: 'image/jpeg',        // 强制转换为 jpg
        convertTypes: ['image/png', 'image/webp'],
        convertSize: 800 * 1024,
        success(result) {
          resolve(result)
        },
        error(err) {
          resolve(false)
        }
      })
    })
  }

  function afterRead(file) {
    const formData = new FormData()
    formData.append('file', file.file)
    filesUpload(formData, 'PROCESS_PHOTO').then(res => {
      file.url = getFullImageUrl(res)
      file.path = res
    }, err => {
      toast.msg(err.message)
    })
  }

  function fetchRecordDetail() {
    loading.value = true
    getRecordsId(route.query.id).then(res => {
      record.value = res
      loading.value = false
    }, err => {
      toast.msg(err.message)
      loading.value = false
    })
  }
  
  function handleSubmit() {
    submitting.value = true
    let obj = {
      recordId: record.value.id,
      description: handleForm.value.description,
      processStatus: handleForm.value.processStatus,
      afterImages: handleForm.value.images.map(img => img.path)
    }
    recordHandle(obj).then(res => {
      showSuccess.value = true
      submitting.value = false
    }, err => {
      toast.msg(err.message)
      submitting.value = false
    })
  }

  const onOversize = () => {
    toast.msg("图片大小不能超过 800KB")
  }
  
  // 工具函数
  const formatTime = (time) => {
    if (!time) return ''
    return new Date(time).toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  }
  
  const getCheckResultType = (result) => {
    return result === 'NORMAL' ? 'success' : 'danger'
  }
  
  const getCheckResultText = (result) => {
    return result === 'NORMAL' ? '正常' : '异常'
  }
  
  const getStatusType = (status) => {
    const types = {
      'PENDING': 'warning',
      'COMPLETED': 'success',
      'NO_NEED': 'primary'
    }
    return types[status] || 'default'
  }
  
  const getStatusText = (status) => {
    const texts = {
      'PENDING': '待处理',
      'COMPLETED': '已处理',
      'NO_NEED': '无需处理'
    }
    return texts[status] || '未知状态'
  }
  
  const getItemsByType = (items, type) => {
    return items?.filter(item => item.formItem.itemType === type) || []
  }
  
  const getFullImageUrl = (path) => {
    return `${baseUrl.value}${path}`
  }
  
  // 页面加载
  onMounted(() => {
    fetchRecordDetail()
  })
  </script>
  
  <style scoped>
  .record-detail {
    min-height: 100vh;
    background-color: #f7f8fa;
    padding-bottom: 24px;
  }
  
  .loading-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 200px;
  }
  
  .info-card {
    background: #fff;
    padding: 16px;
    margin: 12px;
    border-radius: 8px;
  }
  
  .point-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
  }
  
  .point-name {
    font-size: 18px;
    font-weight: 500;
  }
  
  .check-info,
  .inspector-info,
  .time-info {
    margin-bottom: 8px;
    font-size: 14px;
    color: #666;
  }
  
  .check-label {
    margin-right: 8px;
  }
  
  .status-info {
    display: flex;
    align-items: center;
  }
  
  .form-content,
  .handle-records,
  .handle-form {
    background: #fff;
    margin: 12px;
    padding: 16px;
    border-radius: 8px;
  }
  
  .section-title {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 16px;
    padding-bottom: 8px;
    border-bottom: 1px solid #eee;
  }
  
  .form-item {
    margin-bottom: 20px;
  }
  
  .form-item.abnormal {
    font-weight: 500;
  }
  
  .item-label {
    margin-bottom: 12px;
    font-size: 14px;
    color: #323233;
  }
  
  .image-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
    gap: 8px;
    margin-top: 8px;
  }
  
  :deep(.van-field__control) {
    background-color: #f7f8fa !important;
    padding: 8px !important;
    border-radius: 4px;
  }
  
  .handle-record {
    padding: 12px;
    background: #f8f8f8;
    border-radius: 4px;
    margin-bottom: 12px;
  }
  
  .handle-meta {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
    font-size: 14px;
    color: #666;
  }
  
  .handle-status {
    margin-bottom: 8px;
  }
  
  .handle-desc {
    margin: 12px 0;
    white-space: pre-wrap;
    line-height: 1.5;
  }
  
  .handle-images {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-top: 12px;
  }
  
  .upload-section {
    margin: 16px 0;
  }
  
  .upload-label {
    margin-bottom: 8px;
    font-size: 14px;
    color: #666;
  }
  
  .status-select {
    margin: 16px 0;
    display: flex;
    align-items: center;
    gap: 12px;
  }
  
  .status-label {
    font-size: 14px;
    color: #666;
  }
  
  .submit-section {
    margin-top: 24px;
  }
  
  .success-content {
    padding: 24px;
    text-align: center;
  }
  
  .success-icon {
    font-size: 48px;
    color: #07c160;
    margin-bottom: 16px;
  }
  
  :deep(.van-radio-group) {
    flex: 1;
  }
  
  :deep(.van-radio) {
    margin-right: 16px;
  }
  
  :deep(.van-uploader) {
    margin-top: 8px;
  }
  
  :deep(.van-uploader__upload) {
    background-color: #f7f8fa;
  }
  
  :deep(.van-uploader__preview-image) {
    border-radius: 4px;
  }
  
  :deep(.van-field__control) {
    background-color: #f8f8f8;
    padding: 8px;
    border-radius: 4px;
  }
  
  :deep(.van-button--primary) {
    height: 44px;
    font-size: 16px;
  }
  </style>